import 'package:flutter/material.dart';
import 'package:logger/logger.dart';

class EventBusRoute extends StatelessWidget {
  const EventBusRoute({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Event Bus'),
      ),
      body: Center(
        child: Column(
          children: const [
            EventBus1Route(),
            SizedBox(height: 50),
            EventBus2Route(),
          ],
        ),
      ),
    );
  }
}

class EventBus1Route extends StatefulWidget {
  const EventBus1Route({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => EventBus1RouteState();
}

class EventBus1RouteState extends State<EventBus1Route> {
  final logger = Logger(printer: LogfmtPrinter());

  bool flag = false;

  var bus = EventBus();

  @override
  void initState() {
    super.initState();
    bus.on("login", (arg) {
      logger.i("登录成功... $arg");
      setState(() {
        flag = arg;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        const Text("Event Bus 1"),
        const SizedBox(height: 20),
        Text("当前用户登录状态 $flag"),
      ],
    );
  }
}

class EventBus2Route extends StatefulWidget {
  const EventBus2Route({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => EventBus2RouteState();
}

class EventBus2RouteState extends State<EventBus2Route> {
  bool flag = false;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          const Text("Event Bus 2"),
          const SizedBox(height: 20),
          Text("当前用户登录状态 $flag"),
          const SizedBox(height: 20),
          ElevatedButton.icon(
              onPressed: () {
                setState(() {
                  flag = true;
                });
                bus.emit("login", true);
              },
              icon: const Icon(Icons.login),
              label: const Text("登录")),
          const SizedBox(height: 20),
          ElevatedButton.icon(
              onPressed: () {
                setState(() {
                  flag = false;
                });
                bus.emit("login", false);
              },
              icon: const Icon(Icons.logout),
              label: const Text("登出")),
        ],
      ),
    );
  }
}

///订阅者回调签名
typedef void EventCallback(arg);

class EventBus {
  //私有构造函数
  EventBus._internal();

  //保存单例
  static final EventBus _singleton = EventBus._internal();

  //工厂构造函数
  factory EventBus() => _singleton;

  //保存事件订阅者队列，key:事件名(id)，value: 对应事件的订阅者队列
  final _emap = <Object, List<EventCallback>?>{};

  //添加订阅者
  void on(eventName, EventCallback f) {
    _emap[eventName] ??= [f];
    _emap[eventName]!.add(f);
  }

  //移除订阅者
  void off(eventName, [EventCallback? f]) {
    var list = _emap[eventName];
    if (eventName == null || list == null) return;
    if (f == null) {
      _emap[eventName] = null;
    } else {
      list.remove(f);
    }
  }

  //触发事件，事件触发后该事件所有订阅者会被调用
  void emit(eventName, [arg]) {
    var list = _emap[eventName];
    if (list == null) return;
    int len = list.length - 1;
    //反向遍历，防止订阅者在回调中移除自身带来的下标错位
    for (var i = len; i > -1; --i) {
      list[i](arg);
    }
  }
}

//定义一个top-level（全局）变量，页面引入该文件后可以直接使用bus
var bus = EventBus();
